import axios from "axios";
import Vue from 'vue'
import { Message } from "view-design";
import store from '@/store/index';
import router from '@/router/index';
import { getBrowserFingerprint } from '@/common/browser-fingerprint';
import { mdByLogin } from '@/common/common';
let config = {
    baseURL: process.env.VUE_APP_API,
    // baseURL: 'https://nonoonce.hahbuy.com',
    timeout: 60 * 1000, // Timeout
    headers: {
        'Content-Type': 'application/json'
    }
};
console.log("打印Api", process.env.VUE_APP_API);


const _axios = axios.create(config);

_axios.interceptors.request.use(
    function (config) {
        config.headers['Client-Type'] = 'WEB';
        let userTokenInfo = localStorage.getItem('USER_TOKEN');
        if (userTokenInfo) {
            config.headers['X-Access-Token'] = userTokenInfo;
        }
        let localUserConfig = localStorage.getItem("user_language");
        if (localUserConfig) {
            localUserConfig = JSON.parse(localUserConfig);
            config.headers['lang'] = localUserConfig.code ? localUserConfig.code : process.env.VUE_APP_I18N_LOCALE;
        } else {
            config.headers['lang'] = process.env.VUE_APP_I18N_LOCALE;
        }
        let userCurrencyConfig = localStorage.getItem("user_currency");
        if (userCurrencyConfig) {
            userCurrencyConfig = JSON.parse(userCurrencyConfig);
            config.headers['currency'] = userCurrencyConfig.code ? userCurrencyConfig.code : process.env.VUE_APP_CURRENCY;
        } else {
            config.headers['currency'] = process.env.VUE_APP_CURRENCY;
        }

        var client_id = Vue.$cookies.get('_ga') || "";
        if (client_id.length > 6 && client_id.substring(0, 6) == 'GA1.1.') {

            config.headers['x-client-id'] = client_id.substring(6);
        }
        // 本地是否存在，存在就用，不存在重新获取
        const browserLocal = localStorage.getItem('BROWSER_RESULT');
        if (browserLocal) {
            config.headers['browser_device_id'] = browserLocal;
        } else {
            getBrowserFingerprint().then((browserResult) => {
                if (browserResult && browserResult.visitorId) {
                    localStorage.setItem('BROWSER_RESULT', browserResult.visitorId);
                    config.headers['browser_device_id'] = browserResult.visitorId;
                }
            }).catch((error) => {
                console.log('获取浏览器指纹信息失败:', error);
            });
        }

        if (config.url == '/user/register') {
            let asb = mdByLogin(`${config.data.email}${config.data.password}`);
            config.headers['signture'] = asb.signture;
            config.headers['timestamp'] = asb.timestamp;
        }

        return config;
    },
    function (error) {
        // Do something with request error
        return Promise.reject(error);
    }
);

// Add a response interceptor
_axios.interceptors.response.use(function (response) {
    // Do something with response data
    if (response.data.code == 200 || response.data.code == 201 || response.data.code == 0) {
        return response.data;
    } else if (response.data.code == 401) {
        store.commit('resetUserInfo');
        router.push({
            path: '/login'
        });
    } else if (response.data.code == 1002) {
        return response.data;
    } else if (response.data.code == 1010) {
        // 禁搜状态
        return response.data;
    } else {
        // 当messageState 状态是true的时候显示弹窗，处理多个请求，弹窗出多个错误信息
        if (store.state.app.messageState) {
            store.commit('setMessageState');
            Message.error({
                content: response.data.message,
                background: true,
                duration: 8,
                closable: true,
                onClose: () => {
                    store.commit('setMessageState');
                }
            })
        }
        return Promise.reject(response.data);
    }
    return Promise.reject(response.data);
},
    function (error) {
        console.log(error.response);

        // Do something with response error
        if(error.response && error.response.status){
            if (error.response.status == 401) {
                store.commit('resetUserInfo');
                let filterRouter = ['/', '/login', '/register', '/forgot', '/loginToken'];
                let isValueIncluded = filterRouter.includes(window.location.pathname);
                if (!isValueIncluded) {
                    // let to = window.location.pathname + window.location.search;
                    router.push({
                        path: '/login',
                        // query: {
                        //     redirection: to
                        // }
                    });
                }
            }
            if (error.response.data.code == 5000) {
                // 风控弹框
                return Promise.reject(error.response.data);
            } else if (error.response.data.code == 8000) {
                // paypal支付弹框
                return Promise.reject(error.response.data);
            } else if (error.response.data.code == 8001) {
                // klarna支付异常弹框
                return Promise.reject(error.response.data);
            }
        }
        return Promise.reject(error);
    }
);


export default _axios;
